<template>
  <div class="change-password-container">
    <!-- 页面标题 -->
    <div class="page-title">修改密码</div>

    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button type="text" icon="el-icon-arrow-left" @click="goBack">
        返回
      </el-button>
    </div>

    <!-- 表单卡片 -->
    <el-card class="form-card">
      <el-form
          :model="passwordForm"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="password-form"
      >
        <!-- 当前密码 -->
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
              v-model="passwordForm.oldPassword"
              :type="showOldPwd ? 'text' : 'password'"
              placeholder="请输入当前密码"
          >
            <template #suffix>
              <el-icon @click="showOldPwd = !showOldPwd" class="toggle-icon">
                <!-- 使用组件方式而非导入方式 -->
                <el-icon name="eye-off" v-if="showOldPwd" />
                <el-icon name="eye" v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              :type="showNewPwd ? 'text' : 'password'"
              placeholder="请输入新密码"
          >
            <template #suffix>
              <el-icon @click="showNewPwd = !showNewPwd" class="toggle-icon">
                <el-icon name="eye-off" v-if="showNewPwd" />
                <el-icon name="eye" v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              :type="showConfirmPwd ? 'text' : 'password'"
              placeholder="请再次输入新密码"
          >
            <template #suffix>
              <el-icon @click="showConfirmPwd = !showConfirmPwd" class="toggle-icon">
                <el-icon name="eye-off" v-if="showConfirmPwd" />
                <el-icon name="eye" v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm">
            确认修改
          </el-button>
          <el-button @click="resetForm" style="margin-left: 10px;">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElIcon } from 'element-plus'  // 只导入ElIcon组件
import { useUserInfoStore } from '@/stores/userInfo'

// 显示密码状态变量
const showOldPwd = ref(false)
const showNewPwd = ref(false)
const showConfirmPwd = ref(false)

// 表单数据
const passwordForm = ref({
  id: null,
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
const rules = ref({
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 5, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, message: '密码长度至少为6位', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && value === passwordForm.value.oldPassword) {
          return Promise.reject('新密码不能与当前密码相同')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && value !== passwordForm.value.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
})

// 获取用户信息存储
const userInfoStore = useUserInfoStore()

// 页面加载时初始化表单
onMounted(() => {
  try {
    if (userInfoStore && userInfoStore.userInfo && userInfoStore.userInfo.id) {
      passwordForm.value.id = userInfoStore.userInfo.id
    } else {
      ElMessage.error('未获取到用户信息，请重新登录')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  }
})

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      changePassword()
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  showOldPwd.value = false
  showNewPwd.value = false
  showConfirmPwd.value = false
}

// 返回上一页
const goBack = () => {
  try {
    window.history.back()
  } catch (error) {
    console.error('返回失败:', error)
  }
}

// 修改密码API调用
const changePassword = async () => {
  try {
    if (!passwordForm.value.id) {
      ElMessage.error('用户ID不存在，无法修改密码')
      return
    }

    const response = await fetch('/api/admin/changePassword/change.do', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        id: passwordForm.value.id,
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      })
    })

    const result = await response.json()

    if (result && result.code === 200 && result.success === true) {
      ElMessage.success('修改密码成功，请使用新密码登录')
      resetForm()
    } else {
      ElMessage.error(result?.message || '修改密码失败')
    }
  } catch (error) {
    console.error('修改密码请求失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.change-password-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.back-button {
  margin-bottom: 20px;
}

.form-card {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  max-width: 500px;
  margin: 0 auto;
}

.password-form {
  margin-top: 20px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.toggle-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.toggle-icon:hover {
  color: #409eff;
}

@media (max-width: 768px) {
  .form-card {
    padding: 20px;
  }

  .page-title {
    font-size: 18px;
  }
}
</style>